//
//  BHFunlistViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/22.
// 趣玩列表

import UIKit

class BHFunlistViewController: BHBaseViewController {
    
    lazy var filterHeaderView: BHFunlistHeaderFilterView = {
        let view = BHFunlistHeaderFilterView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: BHFunlistHeaderFilterView.height)
        view.delegate = self
        return view
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        layout.sectionInset = .zero
        let view = UICollectionView.buildCollectionView(layout: layout)
        view.register(UINib.init(nibName: "BHMoreFunCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "BHMoreFunCollectionViewCell")
        view.backgroundColor = .white
        view.delegate = self
        view.dataSource = self
        
        return view
    }()
    
    lazy var classFilterView: BHCompetitionDoubleView = {
        let view = BHCompetitionDoubleView.init(type: 0)
        view.delegate = self
        return view
    }()
    
    lazy var areaFilterView: BHCompetitionSortView = {
        let view = BHCompetitionSortView.init(frame: CGRect(x: 0, y: UIScreen.begainY+BHCompetitionFilterView.headerHeight, width: UIScreen.width, height: UIScreen.height-BHCompetitionFilterView.headerHeight-UIScreen.begainY))
        view.delegate = self
        return view
    }()
    
    lazy var sortFilterView: BHCompetitionSortView = {
        let view = BHCompetitionSortView.init()
        view.type = 0
        view.delegate = self
        view.itemArray = BHHomeCityModel.sortArray
        return view
    }()
    
    
    fileprivate var typeModel: BHCommonSortTypeModel = BHCommonSortTypeModel.init()
    fileprivate var funArray: [BHFunListInfoModel] = []
    fileprivate var searchKey: String = ""
    fileprivate var regionCode: String = ""
    fileprivate var sortType: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let rect = CGRect(x: 0, y: BHFunlistHeaderFilterView.height-20, width: UIScreen.width, height: UIScreen.height-BHFunlistHeaderFilterView.height+20)
        self.collectionView.frame = rect
        self.classFilterView.frame = rect
        self.areaFilterView.frame = rect
        self.sortFilterView.frame = rect
        
        self.bh_navigationBar.removeFromSuperview()
        self.view.addSubview(self.filterHeaderView)
        self.view.addSubview(self.collectionView)
        
        self.view.addSubview(self.classFilterView)
        self.view.addSubview(self.areaFilterView)
        self.view.addSubview(self.sortFilterView)
        
        self.queryCityAreaService()
        self.queryFilterTypeService(model: nil)
        self.loadFunService()
        self.collectionView.addLayerCorner(12, 0, .white)
        
        self.collectionView.addRefresh { [weak self] in
            self?.page = 1
            self?.loadFunService()
        }
        
        self.collectionView.addloadMore { [weak self] in
            self?.page += 1
            self?.loadFunService()
        }
    }
 

    override var preferredStatusBarStyle: UIStatusBarStyle {
        get {
            return .lightContent
        }
    }
}

extension BHFunlistViewController: BHFunlistHeaderFilterViewDelegate {
    func filterHeaderDidSelectAct(type: Int) {
        if type == 0 {
            self.navigationController?.popViewController(animated: true)
        }else { // 约玩
            let createVC = BHFunAddFunnyViewController.init()
            self.navigationController?.pushViewController(createVC, animated: true)
        }
    }
    func filterHeaderDidChose(sender: UIButton) {
        let index = sender.tag-100
        self.classFilterView.showOrHide(show: index == 0)
        self.areaFilterView.showOrHide(show: index == 1)
        self.sortFilterView.showOrHide(show: index == 2)
    }
    
    func funHeaderBegainSearch() {
        self.classFilterView.showOrHide(show: false)
        self.areaFilterView.showOrHide(show: false)
        self.sortFilterView.showOrHide(show: false)
        
        self.filterHeaderView.resetAllState()
    }
    
    func funHeaderSearchForKey(key: String) {
        self.searchKey = key
        self.collectionView.mj_header?.beginRefreshing()

    }
}

extension BHFunlistViewController: BHCompetitionSortViewDelegate,BHCompetitionDoubleViewDelegate {
    
    // MARK:切换类型的代理
    func didChoseLeft(model: BHCommonSortTypeModel) {
        self.queryFilterTypeService(model: model)
        
    }
    func didChoseRight(model: BHCommonSortTypeModel) {
        self.typeModel.parentId = model.parentId
        self.typeModel.typeId = model.typeId
       
        self.filterHeaderView.changeIndexBtnText(index: 0, text: "\(model.text) ")
        self.collectionView.mj_header?.beginRefreshing()
    }
    func didTypeChoseClose() {
        self.filterHeaderView.resetAllState()
    }
    
    //区域和排序
    func didSortChoseIndex(model: BHHomeCityModel?, index: Int, view: BHCompetitionSortView) {
        if view == self.areaFilterView {
            self.regionCode = model?.code ?? ""
            self.filterHeaderView.changeIndexBtnText(index: 1, text: "\(model?.name ?? "南京") ")

        }else {
            self.sortType = model?.code ?? "1"
            self.filterHeaderView.changeIndexBtnText(index: 2, text: "\(model?.name ?? "排序") ")
        }
        
        self.collectionView.mj_header?.beginRefreshing()
    }
    
    func didSortViewClose() {
        self.filterHeaderView.resetAllState()
    }
}

extension BHFunlistViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.funArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: UIScreen.width, height: BHMoreFunCollectionViewCell.moreFunHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.funArray[indexPath.row]
        BHRouter.shared.bh_goFunDetail(funId: model.funId)
    }
}

extension BHFunlistViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHMoreFunCollectionViewCell", for: indexPath) as! BHMoreFunCollectionViewCell
        let model = self.funArray[indexPath.row]
        cell.model = model
        return cell
    }
    
}

extension BHFunlistViewController {
    func loadFunService()  {
        let dic = self.appendDic()
        let manager = BHHTTPClient.init()
        manager.get(url: String.fun_list_url, paramters: dic) { (success, errorMsg, responseDic) in
            self.collectionView.endRefresh()
            self.collectionView.endLoading()
            
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let total = BHJsonTool.decodeIntFromDic(dic: result, key: "total")

                if self.page == 1 {
                    self.collectionView.endLoadWithNoMoreData(false)
                    if self.funArray.count != 0 {
                        self.funArray.removeAll()
                    }
                }
                
                let record = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
                for dic in record {
                    let model = BHFunListInfoModel.init()
                    model.parseDic(dic as! [String : Any])
                    self.funArray.append(model)
                }
                self.collectionView.reloadData()
                if self.funArray.count >= total {
                    self.collectionView.endLoadWithNoMoreData(true)
                }
                    
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
        
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = 20
        dic["typeOneValue"] = self.typeModel.parentId
        dic["typeTwoValue"] = self.typeModel.typeId
//        dic["cityId"] = ""
        dic["regionId"] = self.regionCode
        dic["search"] = self.searchKey
        dic["sortType"] = self.sortType
        dic["longitude"] = BHLocationManager.shared.longitude
        dic["latitude"] = BHLocationManager.shared.latitude
        
        return dic
    }
    
    
    func queryFilterTypeService(model: BHCommonSortTypeModel?)  {
        if model == nil {
            BHCommonService.queryTypeOneService(type: 2) { (modelArray) in
                self.classFilterView.leftArray = modelArray
            }
        }else {
            BHCommonService.queryTypeTwoService(parentModel: model!) { (array) in
                model?.childArray = array
                self.classFilterView.rightTable.reloadData()
            }
        }
    }
    
    func queryCityAreaService()  {
        BHCommonService.queryCityAreaService(cityName: nil) { (areaArray) in
    
            self.areaFilterView.itemArray = areaArray
            
        }
    }
}
